package com.learn.sms.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.learn.sms.core.client.SmsClientFactory;
import com.learn.sms.core.property.SmsChannelProperties;
import com.learn.sms.pojo.SmsChannelDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Yu.Tan
 * @date : 2023/7/27 16:57
 * @desc : this class for xxxxx
 **/
@Service
@Slf4j
public class SmsChannelServiceImpl implements SmsChannelService {

    @Resource
    private SmsClientFactory smsClientFactory;

    @PostConstruct
    @Override
    public void initLocalCache() throws Exception {
        // 第一步：查询数据
//        List<SmsChannelDO> channels = smsChannelMapper.selectList();
        List<SmsChannelDO> channels = new ArrayList<>();
        log.info("[initLocalCache][缓存短信渠道，数量为:{}]", channels.size());
        if (CollectionUtil.isEmpty(channels)){
            return;
        }
        // 第二步：构建缓存：创建或更新短信 Client
        List<SmsChannelProperties> propertiesList = channels.stream().map(r -> {
            SmsChannelProperties properties = new SmsChannelProperties();
            BeanUtil.copyProperties(r, properties);
            return properties;
        }).collect(Collectors.toList());
        for (SmsChannelProperties properties : propertiesList) {
            smsClientFactory.createOrUpdateSmsClient(properties);
        }
//        propertiesList.forEach(properties -> smsClientFactory.createOrUpdateSmsClient(properties));
    }


}
